import { defineStore } from 'pinia'
import { ref } from 'vue'
import { Message, Modal } from '@arco-design/web-vue' // Import Modal for confirmation
// 从统一的API入口导入warehouse API
import { warehouseApi } from '@/api'
import http from '@/utils/http'

export const useWarehouseStore = defineStore('warehouse', () => {
    // --- Warehouse State ---
    const warehouseList = ref([])
    const warehouseLoading = ref(false)
    const warehousePagination = ref({
        current: 1,
        pageSize: 10,
        total: 0
    })

    // --- Location State ---
    const locationList = ref([]);
    const locationLoading = ref(false);
    const locationPagination = ref({
        current: 1,
        pageSize: 10,
        total: 0
    })
    const locationQueryParams = ref({ // For filtering location list
        page: 1,
        pageSize: 10,
        warehouse_id: null, // Filter by warehouse
        keyword: '',
        type: '',
        area: '',
        shelf: '',
        level: '',
        status: undefined // Use undefined for 'all' status
    });
    const locationForm = ref({ // For Add/Edit Modal
        id: null,
        warehouse_id: null,
        code: '',
        name: '',
        type: '存储区', // Default type
        area: '',
        shelf: '',
        level: '',
        capacity: null,
        status: 1, // Default enabled (1 for backend)
        remark: ''
    });
    const locationDialogVisible = ref(false);
    const locationDialogTitle = ref('');
    
    // 添加库位缓存机制
    const locationCache = ref({});
    // 缓存过期时间 (10分钟)
    const CACHE_EXPIRY = 10 * 60 * 1000;

    // --- Warehouse Actions ---
    async function fetchWarehouses(params = {}) {
        warehouseLoading.value = true
        try {
            const queryParams = {
                page: warehousePagination.value.current,
                size: warehousePagination.value.pageSize,
                ...params,
            }
            const response = await warehouseApi.getWarehouseList(queryParams)
            if (response && (response.code === 200 || response.code === 0) && response.data) {
                warehouseList.value = response.data.list || []
                warehousePagination.value.total = response.data.total || 0
                Message.success('仓库列表获取成功');
                return response.data
            } else {
                Message.error(response?.message || '获取仓库列表失败')
                return null
            }
        } catch (error) {
            Message.error('请求仓库列表时出错')
            console.error('fetchWarehouses error:', error)
            return null
        } finally {
            warehouseLoading.value = false
        }
    }

    async function createWarehouse(data) {
        // Logic from previous state, assumed correct
        try {
             const response = await warehouseApi.addWarehouse(data);
             if (response.code === 0) {
                 Message.success('创建仓库成功');
                 await fetchWarehouses({ page: 1 }); // Refresh list, go to first page
                 return true;
             } else {
                 Message.error(response.message || '创建仓库失败');
                 return false;
             }
         } catch (error) {
             Message.error('请求创建仓库时出错');
             console.error('createWarehouse error:', error);
             return false;
         }
    }

    async function updateWarehouse(id, data) {
       // Logic from previous state, assumed correct
        try {
            const response = await warehouseApi.updateWarehouse({ ...data, id }); // Ensure ID is in payload if API expects it
            if (response.code === 0) {
                Message.success('更新仓库成功');
                await fetchWarehouses({ page: warehousePagination.value.current }); // Refresh current page
                return true;
            } else {
                Message.error(response.message || '更新仓库失败');
                return false;
            }
        } catch (error) {
            Message.error('请求更新仓库时出错');
            console.error('updateWarehouse error:', error);
            return false;
        }
    }

    async function deleteWarehouse(id) {
       // Logic from previous state, assumed correct
         try {
             const response = await warehouseApi.deleteWarehouse(id);
             if (response.code === 0) {
                 Message.success('删除仓库成功');
                 // Adjust pagination
                  const remainingItems = warehousePagination.value.total - 1;
                  const pageSize = warehousePagination.value.pageSize > 0 ? warehousePagination.value.pageSize : 10;
                  const totalPage = remainingItems > 0 ? Math.ceil(remainingItems / pageSize) : 1;
                  if (warehousePagination.value.current > totalPage && totalPage > 0) {
                      warehousePagination.value.current = totalPage;
                  }
                 await fetchWarehouses();
                 return true;
             } else {
                 Message.error(response.message || '删除仓库失败');
                 return false;
             }
         } catch (error) {
             Message.error('请求删除仓库时出错');
             console.error('deleteWarehouse error:', error);
             return false;
         }
    }

    // --- Location Actions ---
    const resetLocationForm = () => {
        locationForm.value = {
            id: null,
            // 移除依赖主搜索区的仓库ID，新增时应默认为空或由用户选择
            warehouse_id: null, 
            code: '',
            name: '',
            type: '存储区',
            area: '',
            shelf: '',
            level: '',
            capacity: null,
            status: 1,
            remark: ''
        };
    };

    // Fetches locations based on current queryParams (including warehouse_id)
    const fetchLocationList = async () => {
        // 不再要求必须有warehouse_id才能获取列表
        locationLoading.value = true;
        // Update page/size in queryParams before request
        locationQueryParams.value.page = locationPagination.value.current;
        locationQueryParams.value.pageSize = locationPagination.value.pageSize;

        try {
            // Filter out empty string params before sending
            const paramsToSend = {};
             for (const key in locationQueryParams.value) {
                 if (locationQueryParams.value[key] !== '' && locationQueryParams.value[key] !== null && locationQueryParams.value[key] !== undefined) {
                    // Convert status boolean (if used) to 0/1 if needed
                     if (key === 'status' && typeof locationQueryParams.value[key] === 'boolean') {
                         paramsToSend[key] = locationQueryParams.value[key] ? 1 : 0;
                     } else {
                         paramsToSend[key] = locationQueryParams.value[key];
                     }
                 }
             }

            const response = await warehouseApi.getLocationList(paramsToSend);
            console.log('库位列表API响应:', response);
            
            if (response && (response.code === 200 || response.code === 0) && response.data) {
                locationList.value = response.data.list || [];
                locationPagination.value.total = response.data.total || 0;
                return response.data;
            } else {
                Message.error(response?.message || '获取库位列表失败');
                locationList.value = [];
                locationPagination.value.total = 0;
                return null;
            }
        } catch (error) {
            console.error('Error fetching location list:', error);
            Message.error('请求库位列表时出错');
            locationList.value = [];
            locationPagination.value.total = 0;
            return null;
        } finally {
            locationLoading.value = false;
        }
    };

    // Call this when the selected warehouse changes in the filter
    const filterLocationsByWarehouse = (warehouseId) => {
        locationQueryParams.value.warehouse_id = warehouseId;
        locationPagination.value.current = 1; // Reset to first page
        fetchLocationList();
    };


    const handleAddLocation = () => {
        // 移除对主搜索区仓库选择的检查
        // if (!locationQueryParams.value.warehouse_id) {
        //      Message.warning('请先选择一个仓库');
        //      return;
        // }
        resetLocationForm(); // 重置表单，warehouse_id 现在会是 null
        locationDialogTitle.value = '新增库位';
        locationDialogVisible.value = true;
    };

    const handleEditLocation = (row) => {
        resetLocationForm(); // Reset first
        Object.assign(locationForm.value, {
             id: row.id,
             warehouse_id: row.warehouse_id, // Keep track of original warehouse
             code: row.code,
             name: row.name,
             type: row.type,
             area: row.area,
             shelf: row.shelf,
             level: row.level,
             capacity: row.capacity,
             status: row.status,
             remark: row.remark
        });
        locationDialogTitle.value = '编辑库位';
        locationDialogVisible.value = true;
    };

    // Handles the submission logic (validation done in component)
    const submitLocation = async () => {
         let success = false;
         // Convert empty string capacity to null if necessary before sending
          const payload = {
             ...locationForm.value,
             capacity: locationForm.value.capacity === '' || locationForm.value.capacity === undefined ? null : Number(locationForm.value.capacity)
         };

         try {
             if (locationForm.value.id) {
                 // Update - 修改：直接传递整个对象，而不是单独传id和updatePayload
                 const response = await warehouseApi.updateLocation(payload);
                 if (response.code === 0) {
                     Message.success('更新库位成功');
                     success = true;
                 } else {
                     Message.error(response.message || '更新库位失败');
                 }
             } else {
                  // Add - Ensure warehouse_id is set
                  payload.warehouse_id = locationForm.value.warehouse_id; // Get from form model
                  if (!payload.warehouse_id) {
                       Message.error('无法创建库位，未指定所属仓库');
                       return false; // Prevent submission
                   }
                  if (!payload.name) payload.name = payload.code; // Default name to code if empty
                 const response = await warehouseApi.addLocation(payload);
                  if (response.code === 0) {
                     Message.success('新增库位成功');
                     success = true;
                 } else {
                     Message.error(response.message || '新增库位失败');
                 }
             }

             if (success) {
                 locationDialogVisible.value = false;
                 await fetchLocationList(); // Refresh list
                 return true;
             }
         } catch (error) {
             console.error("Error submitting location form:", error);
             Message.error('提交库位信息时发生错误');
         }
         return false; // Indicate failure
    };


    const deleteLocation = (id) => {
        Modal.confirm({
            title: '确认删除',
            content: '确定要删除这个库位吗？此操作不可恢复。',
            okText: '确定删除',
            cancelText: '取消',
            onOk: async () => {
                locationLoading.value = true;
                try {
                    const response = await warehouseApi.deleteLocation(id);
                    if (response.code === 0) {
                        Message.success('删除成功');
                         // Adjust pagination if needed
                        const remainingItems = locationPagination.value.total - 1;
                        const pageSize = locationPagination.value.pageSize > 0 ? locationPagination.value.pageSize : 10;
                        const totalPage = remainingItems > 0 ? Math.ceil(remainingItems / pageSize) : 1;
                        if (locationPagination.value.current > totalPage && totalPage > 0) {
                            locationPagination.value.current = totalPage;
                        }
                        await fetchLocationList(); // Refresh list
                    } else {
                        Message.error(response.message || '删除失败');
                    }
                } catch (error) {
                    console.error("Error deleting location:", error);
                    Message.error('删除库位时发生错误');
                } finally {
                    locationLoading.value = false;
                }
            },
            onCancel: () => {
                 Message.info('已取消删除');
            }
        });
    };

    // For toggling status directly (usually done via Update modal)
    const toggleLocationStatus = async (row) => {
        const newStatus = row.status === 1 ? 0 : 1;
        const statusText = newStatus === 1 ? '启用' : '禁用';
         Modal.confirm({
            title: '确认操作',
            content: `确定要${statusText}库位 "${row.code}" 吗？`,
             okText: `确定${statusText}`,
            cancelText: '取消',
             onOk: async () => {
                 locationLoading.value = true;
                 try {
                     // 修改：将row.id和payload作为单独参数的调用改为传入完整对象
                     const updateData = { ...row, status: newStatus };
                     const response = await warehouseApi.updateLocation(updateData);
                     if (response.code === 0) {
                         Message.success(`${statusText}成功`);
                         await fetchLocationList(); // Refresh list
                     } else {
                          Message.error(response.message || `${statusText}失败`);
                     }
                 } catch (error) {
                     console.error(`Error toggling location status to ${statusText}:`, error);
                     Message.error(`${statusText}库位时发生错误`);
                 } finally {
                      locationLoading.value = false;
                 }
             },
              onCancel: () => {
                 Message.info(`已取消${statusText}操作`);
             }
         });
    };


    const handleLocationPageChange = (page) => {
        locationPagination.value.current = page;
        fetchLocationList();
    };

    const handleLocationSizeChange = (pageSize) => {
        locationPagination.value.pageSize = pageSize;
        locationPagination.value.current = 1;
        fetchLocationList();
    };

    // Triggered by search form in the component
    const handleLocationSearch = () => {
        locationPagination.value.current = 1;
        fetchLocationList();
    };

    // 获取特定仓库下的所有库位
    const getLocationsByWarehouse = async (warehouseId, params = {}, headers = {}) => {
        if (!warehouseId) {
            Message.warning('需要提供仓库ID');
            return [];
        }
        
        // 检查是否强制刷新参数
        const forceRefresh = params?.forceRefresh === true;
        const cacheKey = `locations_${warehouseId}`;
        
        // 获取当前时间
        const now = Date.now();
        
        // 如果不需要强制刷新且缓存存在且未过期，则直接返回缓存数据
        if (!forceRefresh && 
            locationCache.value[cacheKey] && 
            locationCache.value[cacheKey].data && 
            locationCache.value[cacheKey].timestamp && 
            (now - locationCache.value[cacheKey].timestamp) < CACHE_EXPIRY) {
            
            console.log(`[warehouse.store] 使用缓存的库位数据 (${locationCache.value[cacheKey].data.length}条)`);
            return locationCache.value[cacheKey].data;
        }
        
        // 否则，从服务器获取新数据
        try {
            const queryParams = {
                warehouse_id: warehouseId,
                page: 1,
                pageSize: 1000, // 获取足够多的数据，确保能返回所有库位
                ...params,
                // 添加时间戳防止浏览器缓存
                _t: now
            };
            
            console.log('[warehouse.store] 从服务器获取库位, 参数:', queryParams);
            
            // 确保headers是合法的
            const reqHeaders = headers || {};
            
            // 发起请求获取库位数据
            const response = await http.get(`/warehouses/locations`, { 
                params: queryParams,
                headers: reqHeaders
            });
            
            console.log('[warehouse.store] 库位API响应:', response);
            
            if (response && (response.code === 200 || response.code === 0) && response.data) {
                // 处理服务器返回的数据
                const list = response.data.list || [];
                
                // 确保每个库位对象包含完整的属性
                const formattedList = list.map(location => {
                    // 确保数值类型正确
                    const currentQuantity = typeof location.current_quantity === 'string' 
                        ? parseFloat(location.current_quantity) 
                        : (location.current_quantity || 0);
                    
                    const capacity = typeof location.capacity === 'string' 
                        ? parseFloat(location.capacity) 
                        : (location.capacity || 0);
                    
                    // 计算可用容量和使用率
                    const availableCapacity = Math.max(0, capacity - currentQuantity);
                    const usagePercentage = capacity > 0 ? Math.round((currentQuantity / capacity) * 100) : 0;
                    
                    return {
                        ...location,
                        current_quantity: currentQuantity,
                        capacity: capacity,
                        availableCapacity: availableCapacity,
                        usagePercentage: usagePercentage,
                        label: `${location.code} (${currentQuantity}/${capacity || '∞'})`,
                        value: location.id
                    };
                });
                
                // 将数据和时间戳一起保存到缓存中
                locationCache.value[cacheKey] = {
                    data: formattedList,
                    timestamp: now
                };
                
                console.log(`[warehouse.store] 库位数据已缓存 (${formattedList.length}条)`, formattedList[0]);
                return formattedList;
            } else {
                console.error('[warehouse.store] 获取库位列表失败:', response);
                Message.error(response?.message || '获取库位列表失败');
                return [];
            }
        } catch (error) {
            console.error('[warehouse.store] 获取仓库库位列表失败:', error);
            Message.error('获取仓库库位列表失败');
            return [];
        }
    };

    // 清除特定仓库的库位缓存
    const clearLocationCache = (warehouseId) => {
        if (warehouseId) {
            const cacheKey = `locations_${warehouseId}`;
            delete locationCache.value[cacheKey];
            console.log(`[warehouse.store] 已清除仓库${warehouseId}的库位缓存`);
        } else {
            // 清除所有缓存
            locationCache.value = {};
            console.log('[warehouse.store] 已清除所有库位缓存');
        }
    };

    return {
        // Warehouse state
        warehouseList,
        warehouseLoading,
        warehousePagination,
        
        // Location state
        locationList,
        locationLoading,
        locationPagination,
        locationQueryParams,
        locationForm,
        locationDialogVisible,
        locationDialogTitle,
        locationCache,
        
        // Warehouse actions
        fetchWarehouses,
        createWarehouse,
        updateWarehouse,
        deleteWarehouse,
        
        // Location actions
        resetLocationForm,
        fetchLocationList,
        filterLocationsByWarehouse,
        handleAddLocation,
        handleEditLocation, 
        submitLocation,
        deleteLocation,
        toggleLocationStatus,
        handleLocationPageChange,
        handleLocationSizeChange,
        handleLocationSearch,
        getLocationsByWarehouse,
        clearLocationCache
    };
})

export default useWarehouseStore